//
//  Login_VC.m
//  SpendMoney
//
//  Created by  lixinxin on 16/12/28.
//  Copyright © 2016年  lixinxin. All rights reserved.
//

#import "Login_VC.h"
#import "ForgotPassword_VC.h"
#import <Contacts/Contacts.h>
#import <AddressBookUI/AddressBookUI.h>
#import "iPhoneType.h"
#import "LoginPublic.h"
#import <AdSupport/AdSupport.h>
#import "AppDelegate.h"

@interface Login_VC ()<UITextFieldDelegate, ForgotPassword_VCDelegate>

@property (weak, nonatomic) IBOutlet UIView *phone_Vi;

@property (weak, nonatomic) IBOutlet UIView *password_Vi;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (weak, nonatomic) IBOutlet UITextField *phoneNumber_TextField;

@property (weak, nonatomic) IBOutlet UITextField *password_TextField;

@end

@implementation Login_VC {

    BOOL _inB;  // 1:已经进入到注册页，0：未进入到注册页
    BOOL _inForB;  // 1:已经进入到忘记密码页，0：未进入到忘记密码页

    BOOL _didAppearB;  // 1:页面已经加载完 0：页面未加载完
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"登录";
    
    [self initMethod];
    
    if (self.phoneNumber) {
        [self setPhoneTFMethod:self.phoneNumber];
    }
    
    [self.loginButton setBackgroundColor:MAIN_COLOR];
    
//    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    NSLog(@"%@", adId);
}

-(void)setPhoneTFMethod:(NSString *)phoneN {

        self.phoneNumber_TextField.text = [NSString stringWithFormat:@"%@****%@", [phoneN substringToIndex:3], [phoneN substringFromIndex:7]];

}

- (void)initMethod {

    
//    [self setBorMethod:self.phone_Vi];
    [self setBorMethod:self.password_Vi];
//    [self setBorMethod:self.loginButton];

    
    self.password_TextField.returnKeyType = UIReturnKeyJoin;
    self.password_TextField.delegate = self;
    self.phoneNumber_TextField.tag = 212;

    
    self.phoneNumber_TextField.delegate = self;
    self.phoneNumber_TextField.tag = 211;
}


- (void)setBorMethod:(UIView *)vi {

    vi.layer.borderWidth = 1;
    vi.layer.borderColor = UIColorFromRGB(0xe9e9e9).CGColor;
    vi.layer.cornerRadius = 4;
}

#pragma mark - textFieldShould
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // 登录事件
    [self loginMethod];
    
    return YES;
}


#pragma mark - 字数限制
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容

    if (textField.tag == 211) {
        if (toBeString.length > 11) {
            return NO;
        }
        return YES;
    }
    if (toBeString.length > 16) {
        return NO;
    }
    return YES;
}


#pragma mark - 清空
- (BOOL)textFieldShouldClear:(UITextField *)textField {

    if (textField.tag == 211) {
        
        [cSysPlist setObject:@"" forKey:User_Phone];
        
    }
    
    
    return YES;
}



#pragma mark - 登录方法

- (IBAction)loginButtonAction:(UIButton *)sender {
    
    
    [self loginMethod];
}


#pragma mark - 判断登录条件
- (BOOL)loginBeforeMethod {
    if ([self.phoneNumber isEqualToString:@""] || [self.password_TextField.text isEqualToString:@""]) {
        [[Toast makeText:@" 用户名或密码不能为空"] show];
        return NO;
    }
    
    if (![EMAILANDPHONE validateMobile:self.phoneNumber]) {
        [[Toast makeText:@"手机号格式不正确"] show];
        
        return NO;
    }
    
//    if (self.password_TextField.text.length < 4 || self.password_TextField.text.length > 16) {
//        [[Toast makeText:@"密码输入必须4-16位"] show];
//        
//        return NO;
//    }
    return YES;

}


#pragma mark - 登录
- (void)loginMethod {
    
    [self.view endEditing:YES];
    
    if (![self loginBeforeMethod]) {
        return;
    }
     // 判断不要多次点击
    self.loginButton.enabled = NO;
    
    [LoginPublic loginMethod:^(NSDictionary *loginDict, BOOL b, NSString *msg) {
        self.loginButton.enabled = YES;

        if (b) {

             AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            //跳转到首页
            if (self.b) {
                [self dismissViewControllerAnimated:YES completion:^{
                    [app setupRootViewController];
                }];
            } else {
                [app setupRootViewController];
            }
        } else {
            if (msg) {
                [self alertMessage:msg title:@"提示" forAnimation:nil];
            }
        }

    } mobStr:self.phoneNumber pwdStr:self.password_TextField.text];
    
}

#pragma mark - cookie
- (void)cookieMethod {

    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL: [NSURL URLWithString:cLoginJRY]];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:kUserDefaultsCookie];
    

}

// 忘记密码
- (IBAction)forgotPasswordAction:(UIButton *)sender {
    
    if (_didAppearB) {
        _didAppearB = 0;
        ForgotPassword_VC *vc = [[ForgotPassword_VC alloc] init];
        vc.b = self.b;
        vc.title = @"忘记密码";
        vc.tagStr = @"1";
        vc.phoneStr = self.phoneNumber;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


// 注册
- (IBAction)registeredButton:(UIButton *)sender {
    
    if (_didAppearB) {
        _didAppearB = 0;
        ForgotPassword_VC *vc = [[ForgotPassword_VC alloc] init];
        vc.b = self.b;
        vc.title = @"注册";
        vc.tagStr = @"0";
        vc.myDelegate = self;
        
        [self.navigationController pushViewController:vc animated:YES];

    }
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;

//    self.navigationController.navigationBar.translucent = YES;
//    
//    UIImage *image = [UIImage imageNamed:@"transparent.png"];
//    [self.navigationController.navigationBar setBackgroundImage:image
//                                                  forBarMetrics:UIBarMetricsDefault];//代码1
//    [self.navigationController.navigationBar setShadowImage:image];//代码2    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.tabBarController.tabBar.hidden = NO;
//    //    self.navigationController.navigationBarHidden = NO;  // 显示导航栏
//    self.navigationController.navigationBar.translucent = NO;
//    
//    UIImage *image = [UIImage imageNamed:@"transparent.png"];
//    [self.navigationController.navigationBar setBackgroundImage:image
//                                                  forBarMetrics:UIBarMetricsCompact];//代码1
//    
//    
    
}

#pragma mark - 注册完，登录
- (void)registComplete:(NSString *)phoneStr pwdStr:(NSString *)pwdStr {
    
    [self setPhoneTFMethod:phoneStr];
    
    self.password_TextField.text = [NSString stringWithFormat:@"%@", pwdStr];
    
    // 登录事件
    [self loginMethod];
}


#pragma mark - 获取通讯录权限  (只授权，不上传，在提交订单的时候再上传)
- (void)requestAuthorizationForAddressBook {
    
    
    CGFloat device_W = screenSizeWidth;
    if (device_W > 415) { // 拦截iPad
        return;
    }
    
    
    
    // ios9之前
    if (IOS_VERSION_9_BEFORE) {
        
        ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
        ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
        if (status == kABAuthorizationStatusNotDetermined) {
            NSLog(@"还没问");
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error){
                if(granted){
                    NSLog(@"点击同意");
//                    [self phoneNumberMethod];
                    
                }else{
                    NSLog(@"点击拒绝");
                }
            });
        }else if (status == kABAuthorizationStatusAuthorized){
            NSLog(@"已经授权");
//            [self phoneNumberMethod];
            
        }else {
            NSLog(@"没有授权");
            // 弹窗提示去获取权限
        }
        
        CFRelease(addressBookRef);

        
        return;
    }
    
    CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    
    if (authorizationStatus == CNAuthorizationStatusNotDetermined) {
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        
        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (error) {
                return;
            }
            
            if (granted) {
//                [self phoneNumberMethod];
            } else {
                NSLog(@"授权失败, error=%@", error);
            }
        }];
    }
    
    if (authorizationStatus == CNAuthorizationStatusAuthorized) {
//        [self phoneNumberMethod];
        
    }
    
    
}

- (void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];

    _didAppearB = 1;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshData {
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
